import { Service } from 'egg';
import * as crypto from 'crypto';

interface userType {
  id: number
  username: string
  password: string
  createAt: string
  updateAt: string
  email: string
  role: number
}
export default class UserService extends Service {
  public async login(email: string, password: string) {
    const { app, ctx } = this;
    const users = await app.mysql.select('users', { where: { email } });
    if (users.length === 0) return { status: 400, err: '用户名不存在！' };
    const secret = crypto.createHash('sha256').update(password).digest('hex');
    const user = users[0] as userType;
    if (user.password !== secret) return { status: 400, err: '密码错误！' };
    const token = ctx.helper.createToken(app, { email, username: user.username, password: secret });
    return {
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
      },
    };
  }

  public async register(username, password, email) {
    const { app, ctx } = this;
    const selectField = [ 'id', 'username', 'email', 'createAt', 'updateAt' ];
    const sql = `select ${selectField.join(',')} from users where username=\'${username}\' or email=\'${email}\'`;
    const existUsers = await app.mysql.query(sql) as EggMySQLSelectResult;
    if (existUsers.length !== 0) return { status: 400, err: '用户名或者邮箱已经被注册' };
    const secret = crypto.createHash('sha256').update(password).digest('hex');
    const createAt = ctx.helper.getCreateAt();
    const updateAt = ctx.helper.getCreateAt();
    await app.mysql.insert('users', {
      username,
      password: secret,
      email,
      createAt,
      updateAt,
    });
    const users = await app.mysql.select('users', { where: { username } });
    if (users.length === 0) return { status: 400, err: '用户信息未获取到' };
    const user = users[0] as userType;
    return {
      username,
      email,
      id: user.id,
      createAt: user.createAt,
      updateAt: user.updateAt,
    };
  }

  public async findUser(username) {
    const { app } = this;
    const user = await app.mysql.select('users', { where: { username } });
    if (user.length === 0) return { status: 400, err: '用户名不存在！' };
    return { user: user[0] };
  }

  public async getUserPages(options) {
    const { app } = this;
    const user = await app.mysql.select('users', options);
    return { user };
  }

  public async update(options) {
    const { app } = this;
    const currentUser = await app.mysql.select('users', { where: { username: options.username } });
    if (currentUser.length === 0) return { status: 400, err: '用户不存在' };
    const data = {
      id: (currentUser[0] as userType).id,
      ...options,
    };
    const user = await app.mysql.update('users', data);
    if (!user) return { status: 400, err: '更新失败' };
    return { user };
  }
}
